package com.legend.security;

import com.legend.utils.ReturnResult;
import com.legend.utils.Status;
import com.legend.utils.StringUtils;
import com.legend.utils.i18nUtils;
import org.apache.log4j.Logger;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.UUID;

/**
 * Created by ayakatsune on 14-7-10.
 */
public class RepeatSubmitInterceptor extends HandlerInterceptorAdapter {
    Logger logger = Logger.getLogger(AuthorityInterceptor.class);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        ReturnResult result = new ReturnResult();
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            CheckToken annotation = method.getAnnotation(CheckToken.class);
            if (annotation != null) {
                boolean needSaveSession = annotation.makeToken();
                if (needSaveSession) {
                    logger.info("生成一个token。。。。。。");
                  request.getSession(true).setAttribute("token", UUID.randomUUID().toString());
                }
                boolean needRemoveSession = annotation.checkRepeat();
                if (needRemoveSession) {
                    if (isRepeatSubmit(request)) {
                        logger.debug("重复提交了一次数据。。。。。。");
                        result.setMsg(i18nUtils.getVal("100008000"));
                        result.setStatus(Status.ERROR);
                        StringUtils.write(response, result.toString());
                        return false;
                    }
                    logger.debug("不是重复提交，移除。");
                    request.getSession(false).removeAttribute("token");
                }

            }
            return true;

        } else {

            return super.preHandle(request, response, handler);

        }
    }

    private boolean isRepeatSubmit(HttpServletRequest request) {
        String serverToken = (String) request.getSession(true).getAttribute("token");
        if (serverToken == null) {
            return true;
        }
        String clinetToken = request.getParameter("token");

        if (clinetToken == null) {
            return true;
        }
        if (!serverToken.equals(clinetToken)) {
            return true;
        }
        return false;
    }
}
